package com.example.demo.config;

import lombok.Data;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


@Data
//@Configuration
public class MultiDataSource extends AbstractRoutingDataSource {
    /**
     * Determine the current lookup key. This will typically be
     * implemented to check a thread-bound transaction context.
     * <p>Allows for arbitrary keys. The returned key needs
     * to match the stored lookup key type, as resolved by the
     * {@link #resolveSpecifiedLookupKey} method.
     */
    @Override
    protected Object determineCurrentLookupKey () {
        return GlobalContextHolder.getThreadLocal().get();
    }

    private Map<String, DataSource> dataSources;

    @Override
    public Connection getConnection () throws SQLException {
        return determineTargetDataSource().getConnection();
    }

    @Override
    public Connection getConnection (String username, String password) throws SQLException {
        return determineTargetDataSource().getConnection(username, password);
    }

 /*   protected DataSource determineTargetDataSource () {
        return dataSources.get(GlobalContextHolder.getThreadLocal().get());
    }*/

    public void putDataSource (String key, DataSource dataSource) {
        if (Objects.isNull(dataSources)) {
            this.dataSources = new ConcurrentHashMap<>();
        }
        dataSources.put(key, dataSource);
    }


    public Map<String, DataSource> getDataSources () {
        return dataSources;
    }
}
